package com.simulation.controller;

import com.simulation.model.SimulationTask;
import com.simulation.model.SimulationTemplate;
import com.simulation.service.ConfigurationService;
import com.simulation.service.OpcuaServerService;
import com.simulation.service.SimulationTaskManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/simulation")
@CrossOrigin(origins = "*")
public class SimulationController {
    private static final Logger logger = LoggerFactory.getLogger(SimulationController.class);

    @Autowired
    private SimulationTaskManager taskManager;

    @Autowired
    private ConfigurationService configurationService;

    @Autowired
    private OpcuaServerService opcuaServerService;

    /**
     * 获取所有模拟模板
     */
    @GetMapping("/templates")
    public ResponseEntity<List<SimulationTemplate>> getTemplates() {
        List<SimulationTemplate> templates = configurationService.getSimulationTemplates();
        return ResponseEntity.ok(templates);
    }

    /**
     * 根据ID获取模拟模板
     */
    @GetMapping("/templates/{templateId}")
    public ResponseEntity<SimulationTemplate> getTemplate(@PathVariable String templateId) {
        Optional<SimulationTemplate> template = configurationService.getTemplateById(templateId);
        return template.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 创建新的模拟任务
     */
    @PostMapping("/tasks")
    public ResponseEntity<Map<String, Object>> createTask(@RequestBody CreateTaskRequest request) {
        try {
            Optional<SimulationTemplate> template = configurationService.getTemplateById(request.getTemplateId());
            if (template.isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "Template not found: " + request.getTemplateId()));
            }

            String taskId = taskManager.createTask(request.getTaskName(), template.get());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("taskId", taskId);
            response.put("message", "Task created successfully");
            
            logger.info("Created task via API: {} ({})", request.getTaskName(), taskId);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("Error creating task: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "Error creating task: " + e.getMessage()));
        }
    }

    /**
     * 获取所有任务列表
     */
    @GetMapping("/tasks")
    public ResponseEntity<List<SimulationTask>> getTasks() {
        List<SimulationTask> tasks = taskManager.getAllTasks();
        return ResponseEntity.ok(tasks);
    }

    /**
     * 获取指定任务详情
     */
    @GetMapping("/tasks/{taskId}")
    public ResponseEntity<SimulationTask> getTask(@PathVariable String taskId) {
        SimulationTask task = taskManager.getTask(taskId);
        return task != null ? ResponseEntity.ok(task) : ResponseEntity.notFound().build();
    }

    /**
     * 启动任务
     */
    @PostMapping("/tasks/{taskId}/start")
    public ResponseEntity<Map<String, Object>> startTask(@PathVariable String taskId) {
        boolean success = taskManager.startTask(taskId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Task started successfully" : "Failed to start task");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 停止任务
     */
    @PostMapping("/tasks/{taskId}/stop")
    public ResponseEntity<Map<String, Object>> stopTask(@PathVariable String taskId) {
        boolean success = taskManager.stopTask(taskId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Task stopped successfully" : "Failed to stop task");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/tasks/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteTask(@PathVariable String taskId) {
        boolean success = taskManager.deleteTask(taskId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Task deleted successfully" : "Failed to delete task");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 切换任务模拟模式（正常/异常）
     */
    @PostMapping("/tasks/{taskId}/toggle-mode")
    public ResponseEntity<Map<String, Object>> toggleTaskMode(@PathVariable String taskId) {
        boolean success = taskManager.toggleTaskMode(taskId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Task mode toggled successfully" : "Failed to toggle task mode");
        
        if (success) {
            SimulationTask task = taskManager.getTask(taskId);
            response.put("currentMode", task != null ? task.getMode() : null);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 调整数据点值
     */
    @PostMapping("/tasks/{taskId}/adjust-value")
    public ResponseEntity<Map<String, Object>> adjustValue(
            @PathVariable String taskId, 
            @RequestBody AdjustValueRequest request) {
        
        boolean success = taskManager.adjustDataPointValue(taskId, request.getPointName(), request.getValue());
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Value adjusted successfully" : "Failed to adjust value");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取任务统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        Map<String, Object> stats = taskManager.getTaskStatistics();
        return ResponseEntity.ok(stats);
    }

    /**
     * 获取OPC UA服务器状态
     */
    @GetMapping("/opcua/status")
    public ResponseEntity<Map<String, Object>> getOpcuaStatus() {
        Map<String, Object> status = opcuaServerService.getServerStatus();
        return ResponseEntity.ok(status);
    }

    /**
     * 启动OPC UA服务器
     */
    @PostMapping("/opcua/start")
    public ResponseEntity<Map<String, Object>> startOpcuaServer() {
        try {
            opcuaServerService.startServer();
            return ResponseEntity.ok(Map.of("success", true, "message", "OPC UA server started"));
        } catch (Exception e) {
            logger.error("Failed to start OPC UA server: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "Failed to start OPC UA server: " + e.getMessage()));
        }
    }

    /**
     * 停止OPC UA服务器
     */
    @PostMapping("/opcua/stop")
    public ResponseEntity<Map<String, Object>> stopOpcuaServer() {
        try {
            opcuaServerService.stopServer();
            return ResponseEntity.ok(Map.of("success", true, "message", "OPC UA server stopped"));
        } catch (Exception e) {
            logger.error("Failed to stop OPC UA server: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "Failed to stop OPC UA server: " + e.getMessage()));
        }
    }

    /**
     * 重新加载配置
     */
    @PostMapping("/config/reload")
    public ResponseEntity<Map<String, Object>> reloadConfig() {
        try {
            configurationService.reloadConfiguration();
            return ResponseEntity.ok(Map.of("success", true, "message", "Configuration reloaded successfully"));
        } catch (Exception e) {
            logger.error("Failed to reload configuration: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "Failed to reload configuration: " + e.getMessage()));
        }
    }

    // DTO类
    public static class CreateTaskRequest {
        private String taskName;
        private String templateId;

        public String getTaskName() {
            return taskName;
        }

        public void setTaskName(String taskName) {
            this.taskName = taskName;
        }

        public String getTemplateId() {
            return templateId;
        }

        public void setTemplateId(String templateId) {
            this.templateId = templateId;
        }
    }

    public static class AdjustValueRequest {
        private String pointName;
        private Object value;

        public String getPointName() {
            return pointName;
        }

        public void setPointName(String pointName) {
            this.pointName = pointName;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }
    }
} 